import { fa } from 'element-plus/es/locale'
import { createStore } from 'vuex'

const localStorage = window.localStorage;

// 从本地存储中获取数据
const loadDataFromLocalStorage = () => {
  const data = localStorage.getItem('vuex_state');
  if (data) {
    return JSON.parse(data);
  }
  return {};
};

// 将数据保存到本地存储中
const saveDataToLocalStorage = (state:any) => {
  localStorage.setItem('vuex_state', JSON.stringify(state));
};
const store = createStore({
    //状态变量
    state() {
        return {
            ToKen: false,
            NickName: "",

            isShowLogin: true,
            isShowRegister: false,

            fenLeiId:0,
            ...loadDataFromLocalStorage() // 加载本地存储中的数据
        }
    },
    //方法
    mutations: {
        settingNickName(state: any, NickName) {
            state.NickName = NickName
        },
        settingToKen(state: any, ToKen) {
            state.ToKen = ToKen
        },

        //打开登录框
        openLogin(state) {
            state.isShowLogin = true;
        },
        //关闭登录框
        closeLogin(state) {
            state.isShowLogin = false;
        },
        //打开注册框
        openRegister(state) {
            state.isShowRegister = true;
        },
        //关闭注册框
        closeRegister(state) {
            state.isShowRegister = false;
        },

        //分类页面传值
        updateFenLeiId(state, id) {
            state.fenLeiId = id;
        }
    }
})
store.subscribe((mutation, state) => {
    saveDataToLocalStorage(state); // 在每次状态发生变化时保存到本地存储
  });
export default store